﻿using System;
using SysConsole = System.Console;

namespace DBMock.Console
{
    public class Master
    {
        public string ConnectionString { get; set; }

        public Type ModelType { get; set; }

        public int Total { get; set; }

        public int BulkSize { get; set; }

        public Master(string conString, Type type, int total)
        {
            ConnectionString = conString;
            ModelType = type;
            Total = total;

            BulkSize = 300000;
        }

        public void Mock(string conString = null, Type type = null, int? total = null)
        {
            conString = conString ?? ConnectionString;
            type = type ?? ModelType;
            total = total ?? Total;

            if (string.IsNullOrEmpty(conString) || type == null || total == null)
                return;

            int cursorLine = 0;
            SysConsole.WriteLine("Start mock.\n\r");

            var mocker = new DBMock(conString, type, total.Value, BulkSize);

            mocker.Builders.ForEach(builder =>
            {
                builder.StartBuilding += (s, e) =>
                {
                    SysConsole.WriteLine("Start building " + e.TableName + ".");
                    cursorLine = SysConsole.CursorTop;
                };

                builder.PercentBuilded += (s, e) =>
                {
                    SysConsole.SetCursorPosition(0, cursorLine);
                    SysConsole.WriteLine(e.RowsBuilded + " rows builded.");
                };

                builder.EndBuilding += (s, e) =>
                {
                    SysConsole.WriteLine("End building.\n\r");
                };
            });

            mocker.StartCopy += (s, e) =>
            {
                SysConsole.WriteLine("Start copying " + e.Copier.DestinationTableName + ".");
                cursorLine = SysConsole.CursorTop;

                e.Copier.SqlRowsCopied += (s2, e2) =>
                {
                    SysConsole.SetCursorPosition(0, cursorLine);
                    SysConsole.WriteLine(e2.RowsCopied + " rows copied.");
                };
            };

            mocker.EndCopy += (s, e) => { SysConsole.WriteLine("End copying.\n\r"); };

            cursorLine = SysConsole.CursorTop;
            mocker.Mock();

            SysConsole.WriteLine("End mock.");
        }
    }
}
